package com.fzk.blog.settings.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.annotation.SaMode;
import cn.dev33.satoken.stp.StpUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fzk.blog.bean.Blog;
import com.fzk.blog.bean.vo.BlogInfo;
import com.fzk.blog.exception.MyException;
import com.fzk.blog.settings.service.IBlogService;
import com.fzk.blog.utils.ResponseResult;
import org.apache.logging.log4j.util.Strings;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author fzk
 * @date 2021-08-21 10:44
 */
@RestController
public class BlogController {
    @Resource
    private IBlogService blogService;

    @GetMapping("/blog/info")
    public Map<String, Object> getBlogInfoListOrOne(
            @RequestParam(name = "title", required = false) String title,
            @RequestParam(name = "username", required = false) String username,
            @RequestParam(name = "type_id", required = false) Integer typeId,
            @RequestParam(name = "tag", required = false) String[] tag,
            @RequestParam(name = "published", defaultValue = "true") Boolean published,
            @RequestParam(name = "flag", required = false) Integer flag,
            @RequestParam(name = "id", required = false) String blogId
    ) throws JsonProcessingException {
        // 1.判断id
        if (blogId == null) {
            // 2.查询blogInfo列表：此时默认查出content
            // 检查参数
            if (tag == null)
                tag = new String[]{};
            if (flag == null)
                flag = 0;//默认查未被删除的

            List<Integer> tags = new ArrayList<>();
            for (String t : tag) {
                tags.add(Integer.parseInt(t));
            }
            List<BlogInfo> blogInfoList = blogService.getBlogInfoList(title, username, typeId, tags, published, flag);
            return ResponseResult.success("查询成功", blogInfoList);
        } else if (Strings.trimToNull(blogId) == null)
            throw new MyException(400, "参数错误：id:" + blogId);
        else {
            // 3.查询特定blogInfo：此时默认会查出content
            BlogInfo blogInfo = blogService.getBlogInfoById(Integer.parseInt(blogId), published);
            return ResponseResult.success("查询成功", blogInfo);
        }
    }

    @GetMapping("/blog/content")
    public Map<String, Object> getBlogContent(
            @RequestParam("id") int id
    ) {
        // 1.调用service
        String content = blogService.getBlogContent(id);

        return ResponseResult.success("查询成功", content);
    }

    @PostMapping("/blog")
    @SaCheckRole(value = {"root", "publisher"}, mode = SaMode.OR)//检查角色
    public Map<String, Object> insertBlog(
            @RequestParam("title") String title,
            @RequestParam("content") String content,
            @RequestParam("description") String description,
            @RequestParam("type_id") int typeId,
            @RequestParam("create_flag") String createFlag,
            @RequestParam("recommend_level") String recommendLevel,
            @RequestParam("tag") String[] tag,
            @RequestParam("image_url") String imageUrl,
            @RequestParam("published") boolean published
    ) {
        // 1.检查参数
        checkArgs(title, content, description, createFlag, recommendLevel, imageUrl);
        if (tag == null || tag.length == 0)
            throw new MyException(400, "标签不能为空");

        // 2.取出loginId
        int loginId = Integer.parseInt(StpUtil.getLoginId().toString());

        // 3.装入参数
        Blog blog = new Blog();
        blog.setTitle(title);
        blog.setContent(content);
        blog.setDescription(description);
        blog.setTypeId(typeId);
        blog.setCreateFlag(createFlag);
        blog.setRecommendLevel(recommendLevel);
        blog.setImageUrl(imageUrl);
        blog.setPublished(published);

        // 4.调用service
        blogService.insertBlog(blog, tag, loginId);
        String msg = published ? "发布成功" : "已保存到草稿箱";
        return ResponseResult.success(msg);
    }

    @PutMapping("/blog")
    @SaCheckRole(value = {"root", "publisher"}, mode = SaMode.OR)//检查角色
    public Map<String, Object> updateBlog(
            @RequestParam("id") int id,
            @RequestParam("title") String title,
            @RequestParam("content") String content,
            @RequestParam("description") String description,
            @RequestParam("type_id") int typeId,
            @RequestParam("create_flag") String createFlag,
            @RequestParam("recommend_level") String recommendLevel,
            @RequestParam("tag") String[] tag,
            @RequestParam("image_url") String imageUrl,
            @RequestParam("published") boolean published
    ) {
        // 1.检查参数
        checkArgs(title, content, description, createFlag, recommendLevel, imageUrl);
        if (tag == null || tag.length == 0)
            throw new MyException(400, "标签不能为空");

        // 2.取出loginId
        int loginId = Integer.parseInt(StpUtil.getLoginId().toString());

        // 3.装入参数
        Blog blog = new Blog();
        blog.setId(id);
        blog.setTitle(title);
        blog.setContent(content);
        blog.setDescription(description);
        blog.setTypeId(typeId);
        blog.setCreateFlag(createFlag);
        blog.setRecommendLevel(recommendLevel);
        blog.setImageUrl(imageUrl);
        blog.setPublished(published);

        // 4.调用service
        blogService.updateBlog(blog, tag, loginId);
        String msg = published ? "修改成功且发布成功" : "修改成功且已保存到草稿箱";
        return ResponseResult.success(msg);
    }

    @PutMapping(path = "/blog/recycle")
    @SaCheckRole("root")//检查角色
    public Map<String, Object> recycleBlog(
            @RequestParam("id") int id
    ) {
        // 1.取出loginId
        int loginId = Integer.parseInt(StpUtil.getLoginId().toString());
        // 2.调用service
        blogService.recycleBlog(id, loginId);

        return ResponseResult.success("恢复成功");
    }


    @DeleteMapping(path = "/blog")
    @SaCheckRole("root")//检查角色
    public Map<String, Object> deleteBlog(
            @RequestParam("id") int id
    ) {
        // 1.取出loginId
        int loginId = Integer.parseInt(StpUtil.getLoginId().toString());
        // 2.调用service
        String msg = blogService.deleteBlog(id, loginId);

        return ResponseResult.success(msg);
    }

    /**
     * 参数检查
     *
     * @param args 可变形参
     */
    private void checkArgs(String... args) {
        for (String arg : args) {
            if (arg == null || arg.length() == 0)
                throw new MyException(400, "参数错误：" + arg);
        }
    }
}
